<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BOnlineAppointment
 *
 * @author I062261
 */
class BWeEvent extends BApp {

    protected $eventTypeList = array();

    /**
     * 
     * @param type $eventData, array
     * @param type $data
     */
    public function addEvent($eventData, $data = NULL) {

        $mesageList = $eventData['messages'];
        $event = new BWEvent();
        $event->save($eventData);
        foreach ($mesageList as $messageData) {
            $message = new BWMessage();
            $message->save($messageData);
            $items = $message['items'];
            foreach ($items as $itemData) {
                $message->addMessageItem($itemData);
            }
            $event->addMessage($message);
        }
    }

    /**
     * 这个函数用来输入活动的类型以及类型对应的模板， 相对于数据库操作来说，这个
     * 函数做了以下的几件事情：
     * 1）在活动的类型 eventTypeGroup下面里面添加新的具体的type,比如，将 shangpingchuxiao 这个
     * type(group)，添加到 eventTypeGroup下面去
     * 2）在event_message table里面，为event_group添加信息
     * 叫做inputItems， 然后将输入项放进messageItem表里面,其中name就是输入项名称，message_type就是
     * 输入项（group）下面的text，picture等,message_content 为空
     * 3）对应的使用活动类型以及模板的策略是：
     * a>>在eventType group下面找children，就可以找到所有的eventType
     * b>>
     * @param type $typeData
     * @param type $data
     */
    public function addEventType($typeData, $data = NULL) {
        if (is_array($typeData) && $typeData != NULL) {
            $name = isset($typeData['name']) ? $typeData['name'] : NULL;
            $inputItems = isset($typeData['inputItems']) ? $typeData['inputItems'] : array();

            if ($name != NULL) {
                //below code add new event type under eventType group
                $eventTypeGroup = BWEventGroup::find('eventType');
                if ($eventTypeGroup instanceof BWEventGroup) {
                    $eventTypeGroup->addChild($name);
                    $newEventType = $eventTypeGroup->find($name);
                }

                //below code add new types's input items
                if ($newEventType instanceof BWEventGroup) {
                    //first add message for newType
                    $message = new BWMessage();
                    $root = BWMessageGroup::getRoot();
                    //add messageType group
                    $messageType = $root->getChild('messageType');
                    if (!$messageType instanceof BWMessageGroup) {
                        $messageType = $root->addChild('messageType');
                    }
                    //add eventTypeInputItems message type under messageType group
                    $messageType->addChild('eventTypeInputItems');
                    $typeInput = $messageType->getChild('eventTypeInputItems');

                    //create message and under eventTypeInputItems type(group)
                    $inputTypeMessage = new BWMessage();
                    $inputTypeMessage->name = 'eventTypeInputItemsMessage';
                    $inputTypeMessage->save();

                    if ($typeInput instanceof BWMessageGroup)
                        $typeInput->addMember($inputTypeMessage);

                    BWMediaGroup::getRoot()->addChild('mediaType');
                    $mediaType = BWMediaGroup::getRoot()->getChild('mediaType');
                    $textInputType = $mediaType->addChild('textInput');

                    /**
                     * inputItem 就是具体的输入项， 比如：文字输入项，图片输入项等
                     * 这些输入项可能有些特殊的属性，可以用attribute功能
                     */
                    foreach ($inputItems as $inputName => $inputItem) {
                        $mediaInstance = new BWMedia();
                        $mediaInstance->name = $inputItem['name'];
                        if ($inputItem['type'] == 'textInput')
                            $textInputType->addMember($mediaInstance);
                        //比如某个输入项是必须要的，可以加一个必须输入的属性
                        if (isset($inputItem['required']) && $inputItem['required'] != NULL)
                            $mediaInstance->addAttribute('required', $inputItem['required']);
                        //below code add data into tbl_message_media table
                        $messagMediaModel = new BWMMessageMedia();
                        $messagMediaModel->message_group_id = $typeInput->getId();
                        $messagMediaModel->media_id = $mediaInstance->getId();
                        $messagMediaModel->save();
                    }
                }
            }
        }
    }

    /**
     * 这个function用来取活动的类型，这个类型一般来说需要显示在类型的下拉菜单里面
     * @param type $data
     */
    public function getEventTypeList($data = NULL) {
        if ($this->eventTypeList == NULL) {
            $list = array();
            //BWEventGroup::getRoot()->addChild(BWEventGroup::EVENT_TYPE);
            $eventType = BWEventGroup::getRoot()->getChild(BWEventGroup::EVENT_TYPE);
            if ($eventType instanceof BWEventGroup) {
                $typeChildren = $eventType->getChildrenAsLeaf(NULL, TRUE);
                foreach ($typeChildren as $id => $type) {
                    $list[$id] = $type->getFullName('>>');
                }
            }
            $this->eventTypeList = $list;
        }
        return $this->eventTypeList;
    }

    public function getEventList($eventContext = NULL, $data = NULL) {
        //if no argument, return first level of eventTypes
        $list = array();
        if ($eventContext == NULL) {
            $list = BWEvent::findAll();
        }

        return $list;
    }

    public function run($data = NULL) {
        parent::run($data);

        $eventGroup = new BWEventGroup();

        $count = $eventGroup->getRepository()->getCount();

        if ($count < 2) {
            $root = BWEventGroup::getRoot();
            $root->addChild('活动类型');
            $eventType = $root->getChild('活动类型');
            $eventType->addChild('促销');
            $eventType->addChild('促销.家电促销');
            $eventType->addChild('促销.服装促销');
            $eventType->addChild('会员.会员升级');
            $eventType->addChild('会员.会员回馈');
            $eventType->addChild('优惠.品牌优惠');
            $eventType->addChild('会员.投票活动');
            $eventType->addChild('会员.我的抽奖');
        }
    }

    /**
     * this function will call before render operation of followEvent
     * @param type $operation
     * @param type $data
     */
    public function runChongshang_home($operation, $data = NULL) {
        $currentScreen = Blyn::app()->getUIManager()->getCurrentScreen();

        $wxMenu = new BUIWXMenu(Blyn::app()->getActiveOperation());
        $followEventPage = new BUIWXControl();
        $currentScreen->addChildControl($followEventPage);
    }

    public function runFollowEvent($operation, $data = NULL) {
        $senderControl = Blyn::app()->getUIManager()->getSenderControl();
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $currentScreen = Blyn::app()->getUIManager()->getCurrentScreen();

        $wxMenu = new BUIWXMenu(Blyn::app()->getActiveOperation());
        $followEventPage = new BUIWXControl();
        $currentScreen->addChildControl($followEventPage);
        //blow code change layout
        Blyn::app()->getUIManager()->setLayoutView('list_layout');

        if ($wxMenu->isMenuClicked('商社导航|酒店')) {
            $followEventPage->addRenderView('jiudian');
        }
        if ($wxMenu->isMenuClicked('商社导航|汽车')) {
            $followEventPage->addRenderView('qiche');
        }
        if ($wxMenu->isMenuClicked('商社导航|百货')) {
            //$followEventPage->addRenderView('baihuo');
            $followEventPage->addRenderView('binguan');
        }
        if ($wxMenu->isMenuClicked('商社导航|商品促销')) {
            $followEventPage->addRenderView('chongshang_home');
        }
        if ($wxMenu->isMenuClicked('商社导航|电器')) {
            $followEventPage->addRenderView('dianqi');
        }
        if ($wxMenu->isMenuClicked('我的商社|我的抽奖')) {
            $followEventPage->addRenderView('lottery');
        }
        /* 抽奖活动 粗略实现 */
        if ($senderControl->isLinkClicked('参与抽奖')) {
            $eventID = blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventID'); //抽奖活动ID
            $userID = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('userID'); //用户标识ID
            //将用户ID存入当前活动对应的messageList表中.  到抽奖时，将所有参与抽奖的用户提取出来放入一个数组，然后，随机产生数组长度范围内的数字，为抽奖者在数组中的脚标
            //开始抽奖
            $event = new BWEvent($eventID);
            $lotteryMenber = $event->getMessageManager()->getMessageList();
            $stack = array();
            foreach ($lotteryMenber as $member => $id) {
                array_push($stack, $member->getName());
            }
            $finalWin = array();
            for ($i = 0; $i < 3; $i++) {
                if ($i <= count($stack)) {
                    $randWin = rand(0, count($stack));
                    array_push($finalWin, $randWin);
                }
            }

            $finalUserID = array($stack[$finalWin[0]], $stack[$finalWin[1]], $stack[$finalWin[2]]); //最后抽出的三名中奖用户
            echo "<script>alert('$userID 成功参与此次抽奖活动！');</script>";
        }

        if ($senderControl->isLinkClicked('商品信息')) {
            $GoodsID = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('GoodsID'); //商品ID
            $GoodsName = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('GoodsName'); //商品名称
            $GoodsDsc = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('GoodsDsc'); //商品描述
            $followEventPage->addRenderView('GoodView', 'GoodView', array('GoodsID' => $GoodsID, 'GoodsName' => $GoodsName, 'GoodsDsc' => $GoodsDsc));
        }
        if ($senderControl->isLinkClicked('查看活动详情')) {
            $eventID = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventID'); //活动ID
            $event = new BWEvent($eventID);
            $group = $event->getGroup(array('parent' => BWEventGroup::Event_TYPE_Promotion));

            if ($group == FALSE || $group->getName() != '品牌优惠') {
                $followEventPage->addRenderView('huodong_ListView', 'huodong_ListView', array('eventID' => $eventID));
            } else {
                $followEventPage->addRenderView('brand_home', 'brand_home', array('eventID' => $eventID));
            }
            //$followEventPage->addRenderView('huodong_LIstView','','');
        }
        if ($wxMenu->isMenuClicked('我的商社|我的订单')) {
            $eventList = BWEvent::findAll(array('type' => BWEventGroup::Event_TYPE_Member_Pools));
            $followEventPage->addRenderView('myPools_eventList', 'myPools_eventList', array('eventList' => $eventList));
        }
        if ($wxMenu->isMenuClicked('我的商社|投票管理')) {
            $followEventPage->addRenderView('myPools_manage');
        }
        /*
         * 品牌优惠页面处理
         */
        if ($wxMenu->isMenuClicked('商社乐购|品牌优惠')) {
            $followEventPage->addRenderView('brand_list');
        }
        if ($senderControl->isLinkClicked('品牌信息')) {
            $messageID = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('messageID');
            $followEventPage->addRenderView('brand_goodsList', 'brand_goodsList', array('messageID' => $messageID));
        }
        if ($senderControl->isLinkClicked('商品详情')) {
            $mediaID = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('mediaID');
            $GoodsName = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('GoodsName');
            $GoodsDsc = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('GoodsDsc');
            $followEventPage->addRenderView('brand_goods', 'brand_goods', array('mediaID' => $mediaID, 'GoodsName' => $GoodsName, 'GoodsDsc' => $GoodsDsc));
        }
        if ($senderControl->isLinkClicked('showEventList')) {
            //default eventList view
            $eventListView = 'eventList';
            $linkEventListView = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventListView');
            if ($linkEventListView != NULL) {
                $eventListView = $linkEventListView;
            }

            $followEventPage->addRenderView('showEventList', $eventListView);
        }
        /*
         * the  function is used to show list of message 
         */
        if ($senderControl->isLinkClicked('showMessageList')) {
            $parentEventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('parentEventId');
            $parentMessageId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('parentMessageId');
            $data = array();
            if ($parentEventId != NULL)
                $data['parentEventId'] = $parentEventId;
            if ($parentMessageId != NULL)
                $data['parentMessageId'] = $parentMessageId;

            $messageListView = 'messageList';
            $linkMessageListView = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('messageListView');
            if ($linkMessageListView != NULL) {
                $messageListView = $linkMessageListView;
            }

            $followEventPage->addRenderView('showMessageList', $messageListView, $data);
        }
        /*
         * the  function is used to show event
         */
        if ($senderControl->isLinkClicked('showEvent')) {
            $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
            $eventView = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventView');

            $followEventPage->addRenderView('showEvent', $eventView, array('eventId' => $eventID));
        }

        if ($senderControl->isLinkClicked('showMessage')) {
            $messageId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('messageId');
            $messageView = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('messageView');

            $followEventPage->addRenderView('showMessage', $messageView, array('messageId' => $messageId));
        }

        if ($senderControl->isLinkClicked('saveInputValue')) {
            $modelName = Blyn::app()->getUIManager()->getCurrentScreen()->getContextVariable('modelName');
            $inputMedia = $this->saveInputValueFromPostData($modelName);
            $followEventPage->addRenderView('showPoolsResult', 'myPools_poolsResult', array('inputMedia' => $inputMedia));
        }
        if ($senderControl->isLinkClicked('添加投票')) {
            //$eventID = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventID');
            $eventID='0';
            $followEventPage->addRenderView('myPools_addPools', 'myPools_addPools', array('eventId' => $eventID));
        }
    }

    /**
     * this function will call before render operation of manageEvent
     * @param type $operation
     * @param type $data
     */
    public function runManageEvent($operation, $data = NULL) {

        $this->getEventTypeList();

        if (yii::app()->request->isAjaxRequest) {
            $sender = Blyn::app()->getUIManager()->getSenderControl();
            $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
            //$attributes = array();
            //postModel是UI中设定的model的名字，这个名字需要在使用form的view里面设置
            //需要用来获得传递的数据
//            $postModel = Blyn::app()->getUIManager()->getCurrentScreen()->getContextVariable('postModel');
            $postModel = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('postModel');
            $postData = $this->parsedModelData($postModel);
            //postData is $key=>$value list, for $key, format like type_name_surfix
            /*
             * the  function is used to save event
             */
            if ($sender->isAjaxLinkClicked('saveEvent')) {
                //$event = new BWEvent();
                $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
                $event = $this->populateEventFromPostData($postData, $eventId);
                $event->save();
                $eventType = $this->populateEventTypeFromPostData($postData, $eventId);
                if ($eventType instanceof BWEventGroup)
                    $eventType->addMember($event); //tbl_event_group_member

                $mediaList = $this->populateMediaListFromPostData($postData, $eventId);

                //save media to event
                foreach ($mediaList as $media) {
                    $event->getMediaManager()->addMedia($media);
                }

                $inputMediaList = $this->populateInputMediaListFromPostData($postData, $eventId, $event);

                //save inputMedia to event
                foreach ($inputMediaList as $iMedia) {
                    $event->getInputMediaManager()->addInputMedia($iMedia);
                }
            }
            /*
             * the  function is used to save message
             */
            if ($sender->isAjaxLinkClicked('saveMessage')) {

                //$eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
                //indeed message belong to one event or other message, so we should get parent message or parent
                //event like this
                $parentMessageId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('parentMessageId');
                $parentEventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('parentEventId');
                $messageId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('messageId');
                $parent = NULL;

                $message = $this->populateMessageFromPostData($postData, $messageId);
                $message->save();

                if ($parentMessageId != NULL && $parentMessageId > 0) {
                    $parent = new BWMessage($parentMessageId);
                }
                if ($parentEventId != NULL && $parentEventId > 0) {
                    $parent = new BWEvent($parentEventId);
                }

                if ($parent != NULL) {
                    //$event = new BWEvent($eventId);
                    $parent->getMessageManager()->addMessage($message); //添加关连
                }

                $mediaList = $this->populateMediaListFromPostData($postData, $messageId);
                //save media to message
                foreach ($mediaList as $media) {
                    $message->getMediaManager()->addMedia($media);
                }

                $inputMediaList = $this->populateInputMediaListFromPostData($postData, $messageId, $message);

                //save inputMedia to event
                foreach ($inputMediaList as $iMedia) {
                    $message->getInputMediaManager()->addInputMedia($iMedia);
                }
            }
            /*
             * This function is used to show event list
             */
            if ($sender->isAjaxLinkClicked('showEventList')) {
                //default eventList view
                $eventListView = 'eventList';
                $linkEventListView = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventListView');
                if ($linkEventListView != NULL) {
                    $eventListView = $linkEventListView;
                }

                $updateControl->addRenderView('showEventList', $eventListView);
            }
            /*
             * the  function is used to show list of message 
             */
            if ($sender->isAjaxLinkClicked('showMessageList')) {
                $parentEventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('parentEventId');
                $parentMessageId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('parentMessageId');
                $data = array();
                if ($parentEventId != NULL)
                    $data['parentEventId'] = $parentEventId;
                if ($parentMessageId != NULL)
                    $data['parentMessageId'] = $parentMessageId;

                $messageListView = 'messageList';
                $linkMessageListView = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('messageListView');
                if ($linkMessageListView != NULL) {
                    $messageListView = $linkMessageListView;
                }

                $updateControl->addRenderView('showMessageList', $messageListView, $data);
            }
            /*
             * the  function is used to show event
             */
            if ($sender->isAjaxLinkClicked('showEvent')) {
                $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
                $eventView = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventView');

                $updateControl->addRenderView('showEvent', $eventView, array('eventId' => $eventView));
            }

            if ($sender->isAjaxLinkClicked('showMessage')) {
                $messageId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('messageId');
                $messageView = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('messageView');

                $updateControl->addRenderView('showMessage', $eventView, array('messageId' => $messageView));
            }
        }
    }

    /**
     * this function will call before render operation of setupEvent
     * @param type $operation
     * @param type $data
     */
    public function runSetupEvent($operation, $data = NULL) {
        
    }

    /**
     * format of post data:
     * type_class_name[index] or
     * type_class_name or
     * class_name
     * @param type $modelName
     * @return array, return a list for all post data
     */
    protected function parsedModelData($modelName) {
        $parsedData = array();
        $postData = array();
        if (is_string($modelName)) {
            if (isset($_POST[$modelName]))
                $postData = $_POST[$modelName];

            if (is_array($postData) && $postData != NULL) {
                //$name[$index] = $postData[$name][$index];
                foreach ($postData as $key => $value) {
                    $oName = explode("_", $key);
                    if (in_array(strtolower($oName[0]), array('image', 'string'))) {
                        $type = $oName[0];
                        $class = $oName[1];
                        $name = $oName[2];
                        $e = array();
                        $e['type'] = $type;
                        $e['class'] = $class;
                        $e['name'] = $name;
                        $e['value'] = $value;

                        $index = $key;
                        $index = str_replace($oName[0] . '_', '', $index);
                        $index = str_replace($oName[1] . '_', '', $index);
                        $index = str_replace($oName[2] . '_', '', $index);

                        $e['index'] = $index;
                        array_push($parsedData, $e);
                    } else {
                        $type = 'string';
                        $class = $oName[0];
                        $name = $oName[1];

                        $e = array();
                        $e['type'] = $type;
                        $e['class'] = $class;
                        $e['name'] = $name;
                        $index = $key;
                        $index = str_replace($oName[0] . '_', '', $index);
                        $index = str_replace($oName[1] . '_', '', $index);

                        $e['index'] = $index;
                        $e['value'] = $value;
                        array_push($parsedData, $e);
                    }
                }
            }
        }
        return $parsedData;
    }

    protected function saveInputValueFromPostData($modelName) {
        if ($modelName == NULL)
            $modelName = 'BDynamicFormModel';
        $parsedData = array();
        $postData = array();
        if (is_string($modelName)) {
            if (isset($_POST[$modelName]))
                $postData = $_POST[$modelName];

            if (is_array($postData) && $postData != NULL) {
                $inputMedia = NULL;
                foreach ($postData as $key => $value) {
                    $oName = explode("_", $key);
                    $count = count($oName);
                    if ($count == 2) {
                        if (isset($oName[0]) && $oName[0] == 'iMedia') {
                            $inputMediaId = $oName[1];
                            $inputMedia = new BWInputMedia($inputMediaId);
                            $inputMedia->addInputValue($value);
                        }
                    }
                    if ($count == 3) {
                        if (isset($oName[1]) && $oName[1] == 'iMedia') {
                            $type = $oName[0];
                            $inputMediaId = $oName[2];
                            $inputMedia = new BWInputMedia($inputMediaId);
                            $inputMedia->addInputValue($value);
                        }
                    }
                }
                return $inputMedia;
            }
        }
        return false;
    }

    protected function populateEventFromPostData($postData, $eventIndex = NULL, $event = null) {

        if (!$event instanceof BWeEvent) {
            if ($eventIndex == 0)
                $event = new BWEvent();
            else
                $event = new BWEvent($eventIndex);
        }

        foreach ($postData as $data) {
            $type = $data['type'];
            $class = $data['class'];
            $name = $data['name'];
            $value = $data['value'];
            $index = isset($data['index']) ? $data['index'] : NULL;
            if ($class == 'event') {
                if ($eventIndex != NULL) {
                    if (property_exists('BWEvent', $name) && $type == 'string' && $index == $eventIndex) {
                        $event->$name = $value;
                    }
                } else {
                    //if not set eventId
                    if (property_exists('BWEvent', $name) && $type == 'string') {
                        $event->$name = $value;
                    }
                }
            }
        }
        return $event;
    }

    protected function populateMessageFromPostData($postData, $messageIndex = NULL, $message = NULL) {
        if (!$message instanceof BWMessage)
            $message = new BWMessage ();

        foreach ($postData as $data) {
            $type = $data['type'];
            $class = $data['class'];
            $name = $data['name'];
            $value = $data['value'];
            $index = isset($data['index']) ? $data['index'] : NULL;
            if ($class == 'message') {
                if ($messageIndex != NULL && $index != NULL) {
                    if (property_exists('BWMessage', $name) && $type == 'string' && $index == $messageIndex) {
                        $message->$name = $value;
                    }
                } else {
                    //if not set eventId
                    if (property_exists('BWMessage', $name) && $type == 'string') {
                        $message->$name = $value;
                    }
                }
            }
        }
        return $message;
    }

    protected function populateMediaListFromPostData($postData, $mediaIndex = NULL, $media = NULL) {

        $list = array();

        foreach ($postData as $data) {
            $type = $data['type'];
            $class = $data['class'];
            $name = $data['name'];
            $value = $data['value'];
            $index = isset($data['index']) ? $data['index'] : NULL;
            if ($class == 'media') {
                //save string of media
                if ($mediaIndex != NULL && $index != NULL) {
                    if (property_exists('BWMedia', 'name') && $type == 'string' && $index == $mediaIndex) {
                        $media = new BWMedia ();
                        $media->name = $name;
                        $media->content = $value;
                        array_push($list, $media);
                    }
                    //save image of media
                    if (property_exists('BWMedia', 'name') && $type == 'image' && $index == $mediaIndex) {
                        $media = new BWMedia ();
                        $media->name = $name;
                        $media->type = $type;
                        $media->content = 'BDynamicFormModel[' . $type . '_' . $class . '_' . $name . '_' . $index . ']'; //构造image的input的name：BDynamicFormModel[image_media_image_0]
                        array_push($list, $media);
                    }
                } else {
                    //if not set mediaIndex, save string of media
                    if (property_exists('BWMedia', $name) && $type == 'string') {
                        $media = new BWMedia ();
                        $media->name = $name;
                        $media->content = $value;
                        array_push($list, $media);
                    }
                    //save image of media
                    if (property_exists('BWMedia', 'name') && $type == 'image') {
                        $media = new BWMedia ();

                        $media->name = $name;
                        $media->content = 'BDynamicFormModel[' . $type . '_' . $class . '_' . $name . ']'; //构造image的input的name：BDynamicFormModel[image_media_image_0]
                        array_push($list, $media);
                    }
                }
            }
        }
        foreach ($list as $key => $media) {
            if ($media->type == 'string') {
                $media->save();
            }
            if ($media->type == 'image') {
                $tempImage = CUploadedFile::getInstanceByName($media->content);
                if ($tempImage) {
                    //上传文件
                    $newImageName = time() . '_' . rand(1, 9999) . '.' . $tempImage->extensionName;
                    $path = Yii::getPathOfAlias('webroot') . '/upload/';
                    //上传目录
                    if (!is_dir($path)) {
                        mkdir($path);
                        //目录不存在则创建
                    }
                    //The image is valid, you can save it
                    $path = $path . $newImageName;
                    $tempImage->saveAs($path);
                    //$media->name = 'image';
                    $media->content = '/upload/' . $newImageName;
                    $media->save();
                } else {
                    unset($list[$key]);
                }
            }
        }
        return $list;
    }

    protected function populateEventTypeFromPostData($postData, $eventTypeIndex = 0, $type = NULL) {
        if (!$type instanceof BWEventGroup)
            $type = new BWEventGroup ();

        foreach ($postData as $data) {
            $type = $data['type'];
            $class = $data['class'];
            $name = $data['name'];
            $value = $data['value'];
            $index = isset($data['index']) ? $data['index'] : NULL;
            if (strtolower($class) == 'eventtype') {
                $eventTypeId = NULL;
                if ($eventTypeIndex != NULL && $index != NULL) {
                    if ($eventTypeIndex == $index) {
                        if (strtolower($name) == 'eventtypeid')
                            $eventTypeId = $value;
                    }
                }else {
                    if (strtolower($name) == 'eventTypeId')
                        $eventTypeId = $value;
                }
                if ($eventTypeId != NULL && $eventTypeId > 0) {
                    $eventType = new BWEventGroup($eventTypeId);
                    return $eventType;
                }
            }
        }

        return FALSE;
    }

    protected function populateInputMediaListFromPostData($postData, $inputIndex = NULL, $owner = NULL) {
        //first parse inputMedia
        $inputMediaList = array();
        foreach ($postData as $data) {
            $type = $data['type'];
            $class = $data['class'];
            $name = $data['name'];
            $value = $data['value'];
            $index = isset($data['index']) ? $data['index'] : NULL;
            if ($class == 'inputMedia') {
                //save inputmedia
                if ($inputIndex != NULL && $index != NULL && $index == $inputIndex) {
                    if (property_exists('BWInputMedia', 'name') && $type == 'string')
                        if ($index == $inputIndex) {
                            $inputMedia = new BWInputMedia ();
                            $inputMedia->name = $name;
                            $inputMedia->content = $value;
                            if ($owner instanceof BEntity && $owner->getId() != NULL) {
                                $inputMedia->ownerType = get_class($owner);
                                $inputMedia->ownerId = $owner->getId();
                            }
                            $inputMedia->save();
                            $inputMediaList[$name] = $inputMedia;
                            //$inputMediaList[$inputMedia->getId()] = $inputMedia;
                        }
                } else if ($inputIndex == NULL || $index == NULL) {
                    //if not set inputIndex, save string of inputMedia
                    if (property_exists('BWInputMedia', $name) && $type == 'string') {
                        $inputMedia = new BWInputMedia ();
                        $inputMedia->name = $name;
                        $inputMedia->content = $value;
                        if ($owner instanceof BEntity && $owner->getId() != NULL) {
                            $inputMedia->ownerType = get_class($owner);
                            $inputMedia->ownerId = $owner->getId();
                        }
                        $inputMedia->save();
                        $inputMediaList[$name] = $inputMedia;
                        //$inputMediaList[$inputMedia->getId()] = $inputMedia;
                    }
                }
            }
        }

        //parse inputType
        foreach ($postData as $data) {
            $type = $data['type'];
            $class = $data['class'];
            $name = $data['name'];
            $value = $data['value'];
            $index = isset($data['index']) ? $data['index'] : NULL;
            if ($class == 'inputType') {
                if ($inputIndex != NULL && $index != NULL)
                    if ($index == $inputIndex) {
                        $inputMediaName = $data['name'];
                        $inputMedia = $inputMediaList[$inputMediaName];
                        $typeClass = $data['value'];
                        $inputType = new $typeClass($inputMedia);
                        //this function will populate all properties for inputType
                        //will also populate all inputables for inputType
                        $inputType->populateInputTypeByPostData($postData, $index);
                        $inputMedia->setInputType($inputType);
                    } else if ($inputIndex == NULL || $index == NULL) {
                        $inputMediaName = $data['name'];
                        $inputMedia = $inputMediaList[$inputMediaName];
                        $typeClass = $data['value'];
                        $inputType = new $typeClass();
                        $inputType->populateInputTypeByPostData($postData);
                        $inputMedia->setInputType($inputType);
                    }
            }
        }
        //parsed inputable data
        foreach ($postData as $data) {
            $type = $data['type'];
            $class = $data['class'];
            $name = $data['name'];
            $value = $data['value'];
            $index = isset($data['index']) ? $data['index'] : NULL;
            if ($class == 'inputable') {
                $splitIndexList = preg_split('_', $index);
                $count = count($splitIndexList);
                $inputableName = $index;
                if ($count > 1) {
                    $inputableName = $splitIndexList[0];
                    $index = $splitIndexList[$count];
                }
                if ($inputIndex != NULL && $index != NULL && $inputIndex == $index)
                    if ($index == $inputIndex) {
                        $inputMediaName = $data['name'];
                        $inputMedia = $inputMediaList[$inputMediaName];
                        $inputType = $inputMedia->getInputType();
                        $inputType->populateInputableByPostData($data);
                        if ($inputType instanceof BWKeyValueType) {
                            if ($inputableName != NULL) {
                                $inputType->addInputable($inputableName, $value);
                            }
                        }
                    } else if ($inputIndex == NULL || $index == NULL) {
                        $inputMediaName = $data['name'];
                        $inputMedia = $inputMediaList[$inputMediaName];
                        $inputType = $inputMedia->getInputType();
                        if ($inputType instanceof BWKeyValueType) {
                            if ($inputableName != NULL) {
                                $inputType->addInputable($inputableName, $value);
                            }
                        }
                    }
            }
        }
        return $inputMediaList;
    }

}

?>
